#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
import sys

from PyQt4 import QtCore, QtGui

from mainWindow import Ui_MainWindow
import vortindex

class Main(QtGui.QMainWindow):
    def __init__(self):
        super(Main, self).__init__()

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.populate_video_list(vortindex.read_videos())
        QtCore.QObject.connect(self.ui.btn_play, QtCore.SIGNAL('clicked()'), self.play_selected_video)
        QtCore.QObject.connect(self.ui.btn_download, QtCore.SIGNAL('clicked()'), self.download_selected_video)
        QtCore.QObject.connect(self.ui.btn_update, QtCore.SIGNAL('clicked()'), self.get_new_videos)

    def populate_video_list(self, videos):
        """ Add video information for every video to the main list widget
        """
        col_names = vortindex.config['ui']['video_columns'] 
        self.ui.videosList.clear()
        self.ui.videosList.setColumnCount(len(col_names))
        self.ui.videosList.setHeaderLabels(col_names)
        for video in videos:
            video_item = QtGui.QTreeWidgetItem([str(getattr(video, x, '-'))
                                                for x in col_names])
            self.ui.videosList.addTopLevelItem(video_item)

    def play_selected_video(self):
        """ Plays the selected video using external player
        """
        selected = self.ui.videosList.selectedItems()[0]
        video_id = unicode(selected.text(0))     # it breaks if column changes
        vortindex.VortVideo(video_id).load().play()

    def download_selected_video(self):
        """ Download selected video from Vorterix
        """
        selected = self.ui.videosList.selectedItems()[0]
        video_id = unicode(selected.text(0))
        vortindex.VortVideo(video_id).load().download()

    def get_new_videos(self):
        """ Gets information about new videos from Vorterix
        """
        vortindex.update_video_index('new')
        self.populate_video_list(vortindex.read_videos())


def __main__(args):
    app = QtGui.QApplication(args)
    window = Main()
    window.show()

    return app.exec_()

if __name__ == '__main__':
    sys.exit(__main__(sys.argv))
